
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using JYJ.AiYard.StationManagement.TbYardIssuedCards;
using JYJ.AiYard.StationManagement.TbYardIssuedCards.Dtos;
using JYJ.AiYard.StationManagement.TbYardIssuedCards.DomainService;
using JYJ.AiYard.StationManagement.TbYardIssuedCards.Authorization;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.Exporting;
using L._52ABP.Application.Dtos;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using JYJ.AiYard.StationManagement.TbYardMonthCardOnlines;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.StationManagement.YardCommonHald;
using JYJ.AiYard.StationManagement.TbStations;
using System.Threading;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.Common;
using System.Reflection;

namespace JYJ.AiYard.StationManagement.TbYardIssuedCards
{
    /// <summary>
    /// TbYardIssuedCard应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbYardIssuedCardAppService : AiYardAppServiceBase, ITbYardIssuedCardAppService
    {
        #region 构造函数
        private readonly IRepository<TbYardIssuedCard, long> _entityRepository;

        private readonly ITbYardIssuedCardManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        private readonly IRepository<JYJ.AiYard.StationManagement.TbUser.TbUser, long> _entityuserRepository;

        private readonly IListExcelExporter _listExcelExporter;

        private readonly IHostingEnvironment _hostingEnvironment;

        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly IHttpService _httpService;
        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbYardIssuedCardAppService(
        IRepository<TbYardIssuedCard, long> entityRepository
        , ITbYardIssuedCardManager entityManager,
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard,
        IListExcelExporter listExcelExporter,
        IHostingEnvironment hostingEnvironment,
        IHttpContextAccessor httpContextAccessor,
        IHttpService httpService,
        IRepository<JYJ.AiYard.StationManagement.TbUser.TbUser, long> entityuserRepository
        )
        {
            _entityRepository = entityRepository;
            _entityManager = entityManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
            _entityuserRepository = entityuserRepository;
            _listExcelExporter = listExcelExporter;
            _hostingEnvironment = hostingEnvironment;
            _httpContextAccessor = httpContextAccessor;
            _httpService = httpService;
        }
        #endregion

        #region 分页查询
        /// <summary>
        /// 获取TbYardIssuedCard的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.Query)] 
        public async Task<PagedResultDto<TbYardIssuedCardListDto>> GetPaged(GetTbYardIssuedCardsInput input)
		{
            List<long> StationList = new List<long>();
            tbQFilterIssued filterText = input.FilterText.ToObject<tbQFilterIssued>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }

           // tbQFilterIssued filterIssued = Json.ToObject<tbQFilterIssued>(filterText.FilterText);

            bool NoBAccount = _aiYardDbTableIssuedCard.isBAccountQuery((long)AbpSession.UserId);
            // TODO:根据传入的参数添加过滤条件
            var query1 = await _aiYardDbTableIssuedCard.QueryTableIssuedCard(StationList, filterText.filterText, filterText.onlyShowBAccount, NoBAccount);
             
            var query = query1.AsQueryable();
			var count = query.Count();
            if (input.Sorting == "Id")
            {
                query = query.OrderByDescending(o => (o.LastModificationTime));
            }
            else
            {
                query = query.OrderBy(input.Sorting);
            }
            query = query.PageBy(input);


            var entityList = query.ToList();

            var entityListDtos =entityList.MapTo<List<TbYardIssuedCardListDto>>();

            
			return new PagedResultDto<TbYardIssuedCardListDto>(count,entityListDtos);
		}
        /// <summary>
        /// 获取全部数据
        /// </summary>
        /// <param name="FilterText"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<TbYardIssuedCardListDto>> GetIssuedCard(string FilterText)
        {
            // TODO:根据传入的参数添加过滤条件
            bool NoBAccount = _aiYardDbTableIssuedCard.isBAccountQuery((long)AbpSession.UserId);
            var query1 = await _aiYardDbTableIssuedCard.QueryTableIssuedCard(GetCurrenUserOrganizationAndChildrenUnit(), FilterText, false, NoBAccount);

            var query = query1.AsQueryable();
            var count = query.Count();
            query = query.OrderByDescending(o => (o.LastModificationTime));

            var entityList = query.ToList();

            var entityListDtos = entityList.MapTo<List<TbYardIssuedCardListDto>>();


            return new PagedResultDto<TbYardIssuedCardListDto>(count, entityListDtos);
        }
        #endregion

        #region 批量授权查询用户
        /// <summary>
        /// 批量授权查询用户
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.Query)]
        public async Task<List<TbYardIssuedCardDb>> GetAllTbYardIssuedCardDb(long StationId,string endtime1,string endtime2,string order,string by)
        {
            List<long> station = new List<long>();
            station.Add(StationId);
            bool NoBAccount = _aiYardDbTableIssuedCard.isBAccountQuery((long)AbpSession.UserId);
            var query1 = await _aiYardDbTableIssuedCard.QueryTableIssuedCard(station, "", false, NoBAccount);
            if (endtime1 != null && endtime2 != null && endtime1 != "" && endtime2 != "")
            {
                query1 = query1.FindAll(o => ((DateTime)o.EndTime >= DateTime.Parse(endtime1) && (DateTime)o.EndTime <= DateTime.Parse(endtime2)));
            }
            var query = query1.AsQueryable();
            var count = query.Count();
            if (order != null && order.ToUpper() == "ENDTIME")
            {
                if (by != null && by.ToUpper() == "DESC")
                {
                    query = query.OrderByDescending(o => (o.EndTime));
                }
                else
                {
                    query = query.OrderBy(o => (o.EndTime));
                }
            }
            else if (order != null && order.ToUpper() == "CARDNO")
            {
                if (by != null && by.ToUpper() == "DESC")
                {
                    query = query.OrderByDescending(o => (o.CardNo));
                }
                else
                {
                    query = query.OrderBy(o => (o.CardNo));
                }
            }
            else if (order != null && order.ToUpper() == "USER_NAME")
            {
                if (by != null && by.ToUpper() == "DESC")
                {
                    query = query.OrderByDescending(o => (o.User_Name));
                }
                else
                {
                    query = query.OrderBy(o => (o.User_Name));
                }
            }
            else if (order != null && order.ToUpper() == "OBJ_NAME")
            {
                if (by != null && by.ToUpper() == "DESC")
                {
                    query = query.OrderByDescending(o => (o.OBJ_Name));
                }
                else
                {
                    query = query.OrderBy(o => (o.OBJ_Name));
                }
            }
            var entityList = query.ToList();

            var entityListDtos = entityList.MapTo<List<TbYardIssuedCardDb>>();
            
            return entityListDtos;
        }
        #endregion

        #region 单个查询
        /// <summary>
        /// 通过指定id获取TbYardIssuedCardListDto信息
        /// </summary>
        [AbpAuthorize(TbYardIssuedCardPermissions.Query)] 
		public async Task<TbYardIssuedCardListBAccountDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);
            TbYardIssuedCardListBAccountDto bAccountDto = new TbYardIssuedCardListBAccountDto();
            bAccountDto = entity.MapTo<TbYardIssuedCardListBAccountDto>();
            bAccountDto.BAccount = _aiYardDbTableIssuedCard.isHideIssuedRecord(bAccountDto.Id, bAccountDto.Station_ID); 

            return entity.MapTo<TbYardIssuedCardListBAccountDto>();
		}
        #endregion
          
        #region 添加及修改
        /// <summary>
        /// 获取编辑 TbYardIssuedCard
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.Create,TbYardIssuedCardPermissions.Edit)]
		public async Task<GetTbYardIssuedCardBAccountForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
            
			var output = new GetTbYardIssuedCardBAccountForEditOutput();
            TbYardIssuedCardBAccountEditProcDto editDto = new TbYardIssuedCardBAccountEditProcDto();
            //改到这里，等到获取是否B账车牌记录
			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

                Type type = entity.GetType();
                

                var properties = editDto.GetType().GetProperties();
                foreach (var property in properties)
                {
                    var pr2 = entity.GetType().GetProperties();
                 
                    object value = null;
                    foreach (var pr in pr2)
                    {
                        if (pr.Name == property.Name)
                        {
                            value = pr.GetValue(entity);
                            break;
                        }
                    }

                    property.SetValue(editDto, value);
                }

                //editDto = editDto.MapTo<TbYardIssuedCardBAccountEditProcDto>();

                try
                {
                    editDto.Card_IOPower = _aiYardDbTableIssuedCard.GetCard_IOPower(Convert.ToInt64(editDto.Id));
                    editDto.CarPlace = _aiYardDbTableIssuedCard.GetParkingPos(Convert.ToInt64(editDto.User_Id), Convert.ToInt64(editDto.Station_ID));
                     
                    Dictionary<string, string> strUser = _aiYardDbTableIssuedCard.GetPhone(Convert.ToInt64(editDto.User_Id));
                    editDto.Phone = strUser["User_Mobile"].ToString();
                    editDto.User_Dept = Convert.ToInt64(strUser["User_Dept"]);
                    editDto.User_No = strUser["User_No"].ToString();
                    editDto.User_Name = strUser["User_Name"].ToString();
                    editDto.BAccount = _aiYardDbTableIssuedCard.isHideIssuedRecord(Convert.ToInt64(editDto.Id), Convert.ToInt64(editDto.Station_ID));
                }
                catch { }
			}
			else
			{
				editDto = new TbYardIssuedCardBAccountEditProcDto();
                editDto.BeginTime = DateTime.Now.Date;
                
                editDto.CardTypeId = 1409;
                editDto.BAccount = false;
            }

			output.TbYardIssuedCard = editDto;


			return output;
		}

        /// <summary>
        /// 添加或者修改TbYardIssuedCard的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.Create, TbYardIssuedCardPermissions.Edit)]
        public async Task<Dictionary<string, string>> CreateOrUpdate(CreateOrUpdateTbYardIssuedCardInput input,int MonthCount, bool BAccount)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (input.TbYardIssuedCard.Station_ID <= 0)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "请选择确定的场所名称!");
                return result; 
            }
            if (!isPlateLicense(input.TbYardIssuedCard.CardNo))
            {
                result.Add("retype", "-1");
                result.Add("revalue", "非法的车牌号码!");
                return result; 
            }
            if (input.TbYardIssuedCard.Id.HasValue)
            {
                return await Update(input.TbYardIssuedCard, MonthCount,BAccount);
            }
            else
            {
                return await CreateIssuedCard(input.TbYardIssuedCard,MonthCount, BAccount);
            }
        }

        /// <summary>
        /// 存储过程  发放TbYardIssuedCard
        /// </summary>
        [AbpAuthorize(TbYardIssuedCardPermissions.Create)]
        protected async Task<Dictionary<string, string>> CreateIssuedCard(TbYardIssuedCardEditProcDto input,int MonthCount, bool BAccount)
        {
            var entity = input.MapTo<TbYardIssuedCardDb>();
            entity.OP_User_Id = Convert.ToInt32(AbpSession.UserId);
            entity.TenantId = (AbpSession.TenantId == null ? 0 : Convert.ToInt32(AbpSession.TenantId));
            if (input.User_Id > 0)
            {
                //利用人员获取UserNo、UserName
                var query = await _entityuserRepository.GetAsync(Convert.ToInt64(input.User_Id));
                entity.User_No = query.User_No;
                entity.User_Name = query.User_Name;
            }
            else
            {
                entity.User_No = "";
                //entity.User_Name = "测试用户";
            }
            entity.PlateNo = entity.CardNo;
            //entity.User_Dept = 0;
            entity.CarImg = "";
            entity.Issued_Id = 0;

            

            //此处为发放//延期操作   发行0   延期1
            entity.Delay = false;

            var result = await _aiYardDbTableIssuedCard.CreateIssuedCard(entity, MonthCount,BAccount);
            string value = "";
            if (result.TryGetValue("retype", out value) && value!="-1" && entity.Account==0)
            {
                _aiYardDbTableIssuedCard.AddIssuedCardPay((long)entity.Station_ID, long.Parse(value), 0, (DateTime)entity.EndTime, "发行", 0, 0, 0, "现金");
            }
            return result;
        }


        /// <summary>
        /// 编辑TbYardIssuedCard
        /// </summary>
        [AbpAuthorize(TbYardIssuedCardPermissions.Edit)]
        protected virtual async Task<Dictionary<string, string>> Update(TbYardIssuedCardEditProcDto input, int MonthCount, bool BAccount)
        {
            //TODO:更新前的逻辑判断，是否允许更新          
            var entity = input.MapTo<TbYardIssuedCardDb>();
            entity.Delay = false;  //发行改卡 
            entity.CarImg = "";
            entity.Issued_Id = input.Id;
            entity.OP_User_Id = Convert.ToInt32(AbpSession.UserId);
            entity.TenantId = (AbpSession.TenantId == null ? 0 : Convert.ToInt32(AbpSession.TenantId));
            return await _aiYardDbTableIssuedCard.CreateIssuedCard(entity, MonthCount, BAccount);
        }
        #endregion

        #region 其它查询
        public List<TbrYardUserDto> GetUserList(string QueryUserName,long StationId)
        {
            var strUser = new List<TbrYardUserDto>();
            strUser = _aiYardDbTableIssuedCard.GetUserList(StationId, QueryUserName);
            return strUser;
        }

        public Dictionary<string, string> gettestUser(long StationId)
        {
            var strUser = new Dictionary<string, string>();
            strUser = _aiYardDbTableIssuedCard.gettestUser(StationId);
            return strUser;
        }
        #endregion

        #region 注销
        /// <summary>
        /// 注销TbYardIssuedCard信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.CardLogout)]
        public async Task CardLogout(TbYardIssuedCardListDto input)
        {
            if (input.Id >0)
            {
                //不存在ID，提示无权注销
                var entity = input.MapTo<TbYardIssuedCardDb>();
                entity.OP_User_Id = Convert.ToInt32(AbpSession.UserId);
                entity.Issued_Id = input.Id;
                await _aiYardDbTableIssuedCard.CardLogoutIssuedCard(entity);
            }
            else
            {
                throw new UserFriendlyException("无ID，无法注销！");
            }
        }
        #endregion

        #region 批量授权 
        /// <summary>
        /// 批量授权
        /// </summary>
        [AbpAuthorize(TbYardIssuedCardPermissions.BatchAuthorization)]
        public Dictionary<string, string> BatchAuthorizationByIds(List<long> input,string selectedDevices)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            int TenantId = Convert.ToInt32(AbpSession.TenantId);
            string strError = "";
            string strSuccess = "";
            foreach(long lk in input)
            {
                
                if (_aiYardDbTableIssuedCard.BatchAuthorizationIssuedCard(lk, TenantId, 0, selectedDevices) == -1)
                {
                    strError += lk.ToString() + "错误";
                }
                else
                    strSuccess += lk.ToString() + ",";
            }
            if (!string.IsNullOrEmpty(strError))
            {
                result.Add("retype", "-1");
                result.Add("revalue", strError);
                return result;
            }
            else
            {
                result.Add("retype", "1");
                result.Add("revalue", "批量授权成功");
            }
            Logger.Error(string.Format("批量授权{0},选择设备{2},未成功{1}", strSuccess, string.IsNullOrEmpty(strError) ? "无" : strError, selectedDevices)); 
            return result;
        }
        #endregion

        #region 批量延期

        /// <summary>
        /// 批量延期
        /// </summary>
        [AbpAuthorize(TbYardIssuedCardPermissions.BatchDelay)]
        public async Task<Dictionary<string, string>> BatchDelayByIds(List<long> input, string selectDate)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            int TenantId = Convert.ToInt32(AbpSession.TenantId);
            string strError = "";
            string strSuccess = "";
            foreach (long lk in input)
            {
                //不存在ID，提示无权延期  
                var entityDto = await _aiYardDbTableIssuedCard.QueryTableIssuedCardById(lk);


                entityDto.EndTime = Convert.ToDateTime(selectDate);
                entityDto.OP_User_Id = Convert.ToInt32(AbpSession.UserId);
                entityDto.Issued_Id = lk;
                entityDto.Delay = true;  //延期卡
                entityDto.TenantId = (AbpSession.TenantId == null ? 0 : Convert.ToInt32(AbpSession.TenantId));

                 


                var result2 = await _aiYardDbTableIssuedCard.CreateIssuedCard(entityDto, 0,false);
                string value = "";
                if (result.TryGetValue("retype", out value) && value != "-1" && entityDto.Account == 0)
                {
                    _aiYardDbTableIssuedCard.AddIssuedCardPay((long)entityDto.Station_ID, entityDto.Id, 0, ((DateTime)entityDto.EndTime).Date, "延期", 0, 0, 0, "现金");
                } 
                strSuccess += lk.ToString() + ",";
            }
            if (!string.IsNullOrEmpty(strError))
            {
                result.Add("retype", "-1");
                result.Add("revalue", strError);
                return result;
            }
            else
            {
                result.Add("retype", "1");
                result.Add("revalue", "批量延期成功");
            }
            Logger.Error(string.Format("批量延期{0},选择日期{2},未成功{1}", strSuccess, string.IsNullOrEmpty(strError) ? "无" : strError, selectDate));
            return result;
        }
        #endregion

        #region 批量注销

        /// <summary>
        /// 批量延期
        /// </summary>
        [AbpAuthorize(TbYardIssuedCardPermissions.BatchCardLogout)]
        public async Task<Dictionary<string, string>> BatchCardLogoutByIds(List<long> input, string selectDate)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            int TenantId = Convert.ToInt32(AbpSession.TenantId);
            string strError = "";
            string strSuccess = "";
            foreach (long lk in input)
            {
                try
                {
                    var entity = await _aiYardDbTableIssuedCard.QueryTableIssuedCardById(lk);
                    entity.OP_User_Id = Convert.ToInt32(AbpSession.UserId);
                    entity.Issued_Id = lk;
                    await _aiYardDbTableIssuedCard.CardLogoutIssuedCard(entity);
                }
                catch (Exception ex)
                {
                    strError = strError + "," + lk;
                }
            }
            if (!string.IsNullOrEmpty(strError))
            {
                result.Add("retype", "-1");
                result.Add("revalue", strError.Trim(',') + "未注销成功");
                return result;
            }
            else
            {
                result.Add("retype", "1");
                result.Add("revalue", "批量注销成功");
            }
            Logger.Error(string.Format("批量延期{0},选择日期{2},未成功{1}", strSuccess, string.IsNullOrEmpty(strError) ? "无" : strError, selectDate));
            return result;
        }
        #endregion

        #region 批量导入车牌
        /// <summary>
        /// 批量导入车牌
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns> 
        [AbpAuthorize(TbYardIssuedCardPermissions.BatchLoadCardNo)]
        public async Task<Dictionary<string, string>> BatchLoadCardNo(IFormFile files)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            string webRootPath = _hostingEnvironment.WebRootPath; 

            try
            {
                if (files == null || files.Length <= 0)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "请选择需要上传的文件");
                    return result;
                }
                var formFile = files;
                if (formFile.Length > 0)
                {
                    string fileExt = Path.GetExtension(formFile.FileName); //文件扩展名，不含“.”
                    if (fileExt != ".xls" && fileExt != ".xlsx")
                    {
                        result.Add("retype", "-1");
                        result.Add("revalue", "请选择Excel文件格式");
                        return result;
                    }
                    long fileSize = formFile.Length; //获得文件大小，以字节为单位
                    string name = Guid.NewGuid().ToString();
                    string newName = name + fileExt; //新的文件名
                    var fileDire = webRootPath + string.Format("/Temp/Upload/", "");
                    if (!Directory.Exists(fileDire))
                    {
                        Directory.CreateDirectory(fileDire);
                    }

                    var filePath = fileDire + newName;

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                    result.Add("retype", "1");
                    result.Add("revalue", name);
                    return result;
                }
                else
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "上传的文件为空");
                    return result;
                }
            }
            catch (Exception ex)
            {
                result.Add("retype", "-1");
                result.Add("revalue", ex.Message);
                return result;
            } 
        }
        /// <summary>
        /// 批量导入车牌
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.BatchLoadCardNo)]
        public async Task<Dictionary<string, string>> BatchLoadCardNoByFileName(string filename,long StationId)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                string webRootPath = _hostingEnvironment.WebRootPath;
                var fileDire = webRootPath + string.Format("/Temp/Upload/", "");

                var filePath = fileDire + filename+".xls";
                if (!File.Exists(filePath))
                {
                    filePath = fileDire + filename + ".xlsx";
                    if (!File.Exists(filePath)) {
                        result.Add("retype", "-1");
                        result.Add("revalue", "上传的文件不存在");
                        return result;
                    }
                }
                int OP_User_Id = Convert.ToInt32(AbpSession.UserId);
                int TenantId = Convert.ToInt32(AbpSession.TenantId);
                return await _aiYardDbTableIssuedCard.BatchLoadCardNo(filePath, StationId, TenantId, OP_User_Id);
            }
            catch (Exception ex)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "上传的文件为空");
                return result;
            }
        }
        #endregion

        #region 获取月卡延期规则
        public async Task<List<TbYardMonthCardOnline>> GetTbYardMonthCardOnlines(long StationId)
        {
            return await _aiYardDbTableIssuedCard.GetTbYardMonthCardOnlines(StationId);
        }
        #endregion

        #region 按包月规则计算
        /// <summary>
        /// 计算包月
        /// </summary>
        /// <param name="IssuedId"></param>
        /// <param name="Station_Id"></param>
        /// <param name="CardTypeId"></param>
        /// <param name="MonthCount"></param>
        /// <returns></returns>
        public async Task<TbYardIssuedMonthOnlineResult> CaleMonthCardOnlines(long IssuedId, long Station_Id, int CardTypeId, int MonthCount)
        {
            var entity =  await _aiYardDbTableIssuedCard.CaleMonthCardOnlines(IssuedId, Station_Id, CardTypeId, MonthCount);
            return entity.MapTo<TbYardIssuedMonthOnlineResult>();
        }
        #endregion

        #region 延期
        /// <summary>
        /// 延期TbYardIssuedCard信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.CardDelay)]
        public async Task<Dictionary<string,string>> CardDelay(CreateOrUpdateTbYardIssuedCardInput input,int MonthCount)
        {
            var entity1 = input.TbYardIssuedCard;
            if (entity1.Id > 0)
            {
                //不存在ID，提示无权延期
                var entity = entity1.MapTo<TbYardIssuedCardDb>();
                entity.OP_User_Id = Convert.ToInt32(AbpSession.UserId);
                entity.Issued_Id = entity.Id;
                entity.Delay = true;  //延期卡
                entity.TenantId = (AbpSession.TenantId == null ? 0 : Convert.ToInt32(AbpSession.TenantId));
                var result = await _aiYardDbTableIssuedCard.CreateIssuedCard(entity, MonthCount,false);
                string value = "";
                if (result.TryGetValue("retype", out value) && value != "-1" && entity.Account == 0) 
                {
                    _aiYardDbTableIssuedCard.AddIssuedCardPay((long)entity.Station_ID, entity.Id, 0, ((DateTime)entity.EndTime).Date, "延期", 0, 0, 0, "现金");
                }
                return result;
            }
            else
            {
                throw new UserFriendlyException("记录编号错误，无法延期！");
            }
        }
        #endregion

        #region 导出
        /// <summary>
        /// 导出为excel表,等待开发。
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbYardIssuedCardPermissions.ExportExcel)]
        public async Task<FileDto> GetToExcel()
        {
            bool NoBAccount = _aiYardDbTableIssuedCard.isBAccountQuery((long)AbpSession.UserId);
            var query1 = await _aiYardDbTableIssuedCard.QueryTableIssuedCard(GetCurrenUserOrganizationAndChildrenUnit(), "", false, NoBAccount); 
            return _listExcelExporter.ExportToExcelByYardIssuedCard(query1);
        }
        #endregion

        #region 判断是否合法车牌号码
        /// <summary>
        /// 判断是否合法车牌号码
        /// </summary>
        /// <param name="PlateNo"></param>
        /// <returns></returns>
        public static bool isPlateLicense(string PlateNo)
        {
            try
            {
                if (PlateNo == "_无_" || PlateNo == "无" || PlateNo.Contains("无"))
                {
                    return true;
                }
                string Value = "粤军警WJ港京津沪冀豫晋鲁桂滇黔川苏浙湘鄂新藏黑皖闽琼辽陕甘青吉蒙渝宁赣贵云甲乙丙丁戊己庚辛壬癸学澳港挂";
                if (PlateNo.Length < 7 || PlateNo.Length > 8)
                {
                    return false;
                }
                for (int i = 0; i < PlateNo.Length; i++)
                {
                    if (PlateNo.Substring(i, 1).ToUpper() == "I"
                        || PlateNo.Substring(i, 1).ToUpper() == "O")
                    {
                        return false;
                    }
                }
                if (!Value.Contains(PlateNo.Substring(0, 1)))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 扫码支付
        public async Task<string> codePay(decimal Amount,decimal PurMoney,decimal YHMoney, int RecordId, string PlateNo, 
            long Station_Id,string EndTime,string OpType, string BarCode)
        {
            try
            {
                int year = int.Parse(EndTime.Substring(0, 4));
                int month = int.Parse(EndTime.Substring(4, 2));
                int day = int.Parse(EndTime.Substring(6, 2));
                DateTime dateTime = new DateTime(year, month, day);
                if (BarCode == "现金")
                {
                    await _aiYardDbTableIssuedCard.AddIssuedCardPay(Station_Id, RecordId, 0, dateTime, OpType, PurMoney, Amount, YHMoney, BarCode);
                    return "支付成功";
                }
                string host = _httpContextAccessor.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
                string hostComputerName = System.Net.Dns.GetHostName().Trim();
#if DEBUG
                host = "pay.aiyard.cn";
                hostComputerName = "iZcivihhk70dkhZ";
#endif
                string ApiUrl = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/";

                List<TbStation> tbs = _aiYardDbTableIssuedCard.GetTbStations(Station_Id);
                string Station_No = tbs[0].Station_No;
                string Station_Name = tbs[0].Station_Name;
                string Md5Key = tbs[0].Station_MD5Key;
                string Pay_subject = PlateNo + "包月续费[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]";
                CCBJHPayResponse cCBJH = new CCBJHPayResponse();
                string result = Run(Station_Id,
                    Station_No,
                    Station_Name,
                    1,
                    hostComputerName,
                    hostComputerName,
                    BarCode, Amount, RecordId, Pay_subject,
                    ApiUrl,
                    Md5Key, ref cCBJH);
                if (result == "等待轮询")
                {

                    int maxlxtime = 1;
                    while (true)
                    {
                        try
                        {
                            if (maxlxtime > 10)
                            {
                                result = "支付超时";
                                break;
                            }

                            result = RunCCBAge(Station_Id,
                            Station_No,
                            Station_Name,
                            1,
                            hostComputerName,
                            hostComputerName,
                            BarCode, Amount, RecordId, Pay_subject,
                            ApiUrl,
                            Md5Key, ref cCBJH);
                            if (result == "支付成功")
                            {
                                break;
                            }
                            else if (result == "等待轮询")
                            {
                                maxlxtime++;
                                Thread.Sleep(1000);
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            result= "轮询异常";
                        }
                    }
                }
#if DEBUG
                string PayType = "微信";
                
                if (BarCode.StartsWith("28"))
                {
                    PayType = "支付宝";
                }
               await  _aiYardDbTableIssuedCard.AddIssuedCardPay(Station_Id, RecordId, 0, dateTime, OpType, PurMoney, Amount, YHMoney, PayType);
#else
                if (result == "支付成功")
                { 
                    string PayType = "微信";
                    if (BarCode.StartsWith("28")) {
                        PayType = "支付宝";
                    }
                    await  _aiYardDbTableIssuedCard.AddIssuedCardPay(Station_Id, RecordId, 0, dateTime, OpType, PurMoney,Amount,YHMoney,PayType);
                }
#endif
                return result;
            }
            catch (Exception ex)
            {
                return "支付异常";
            }
        }

        #region 扫码支付
        private string Run(long Station_Id, string Station_No, string Station_Name, long Client_Id, string Client_No, string Client_Name,
                                         string AUTHNO, decimal Amount, int IN_ID, string Pay_subject, string _ApiUrl, string _MD5Key,
                                         ref CCBJHPayResponse cCBJHPayLX)
        {
            try
            {
                 
                //准备扫码支付
                YardPayRequest request = new YardPayRequest();
                request.Station_Id = Station_Id;
                request.Station_No = Station_No;
                request.Station_Name = Station_Name;
                request.Client_Id = Client_Id;
                request.Client_No = Client_No;
                request.Client_Name = Client_Name;
                request.yardPay = new YardPayModels();
                request.yardPay.Amount = (int)Math.Truncate(Amount * 100);
                request.yardPay.ApiVersion = "V1.0";
                request.yardPay.AUTHNO = AUTHNO;
                request.yardPay.goods_tag = "停车费";
                request.yardPay.paysource = Paysource.YQ;
                request.yardPay.Pay_subject = Pay_subject;
                request.yardPay.RecordId = IN_ID;
                string nonce = Guid.NewGuid().ToString();
                request.Nonce = nonce;
                request.Sign = MD5.MD5Encrypt(request.yardPay.ToJson().ToUpper() + nonce.ToLower() + _MD5Key.ToLower()).ToLower();// Result.AddSign(request.yardPay.ToJson(), request.Nonce, _MD5Key);
                Logger.Info("扫码支付-->Run-->请求串-->" + request.ToJson());
                string response = _httpService.Post(request.ToJson(), _ApiUrl + "Api/v1.0/BarCodePay/codePay", 120);
                Logger.Info("扫码支付-->Run-->返回串-->" + response);
                ApiReturn apireturn = Json.ToObject<ApiReturn>(response);
                if (apireturn.result == 200)
                {
                    YardResponseResult check = Json.ToObject<YardResponseResult>(response);
                    string sign = MD5.MD5Encrypt(("[" + response.Split('[')[1].Split(']')[0] + "]").ToUpper() + apireturn.nonce.ToLower() + _MD5Key.ToLower()).ToLower();
                    if (sign != apireturn.sign)
                    {
                         
                        return "扫码失败，返回结果验签错误";
                    } 
                    return "支付成功";

                }
                else if (apireturn.result == 201)
                {
                    CCBJHPayResponseResult check = Json.ToObject<CCBJHPayResponseResult>(response);
                    string sign = MD5.MD5Encrypt(check.msg.ToJson().ToUpper() + apireturn.nonce.ToLower() + _MD5Key.ToLower()).ToLower();
                    if (sign != apireturn.sign)
                    { 
                        return "扫码失败，返回结果验签错误";
                    }
                    cCBJHPayLX = check.msg;
                    return "等待轮询";
                }
                else
                {
                    return "支付失败";
                }
            }
            catch (Exception ex)
            { 
                return "支付失败";
            }
        }
        #endregion

        #region 建行扫码轮询
        private string RunCCBAge(long Station_Id, string Station_No, string Station_Name, long Client_Id, string Client_No, string Client_Name,
                                         string AUTHNO, decimal Amount, int IN_ID, string Pay_subject, string _ApiUrl, string _MD5Key,
                                         ref CCBJHPayResponse cCBJHPayLX)
        {
            try
            {
                //准备扫码支付
                CCBJHPayRequest request = new CCBJHPayRequest();
                request.Station_Id = Station_Id;
                request.Station_No = Station_No;
                request.Station_Name = Station_Name;
                request.Client_Id = Client_Id;
                request.Client_No = Client_No;
                request.Client_Name = Client_Name;
                request.cCBWG = new CCBJHPayModels();
                request.cCBWG.Amount = (int)Math.Truncate(Amount * 100);
                request.cCBWG.ORDERID = cCBJHPayLX.OUT_TRADE_NO;
                request.cCBWG.QRCODETYPE = tradeCodetoCode(cCBJHPayLX.QRCODETYPE);
                request.cCBWG.QRYTIME = cCBJHPayLX.WAITTIME + 1;
                request.cCBWG.paysource = Paysource.YQ;
                request.cCBWG.Pay_subject = Pay_subject;
                request.cCBWG.RecordId = IN_ID;
                request.cCBWG.TRACEID = cCBJHPayLX.TRACEID;
                string nonce = Guid.NewGuid().ToString();
                request.Nonce = nonce;
                request.Sign = MD5.MD5Encrypt(request.cCBWG.ToJson().ToUpper() + nonce.ToLower() + _MD5Key.ToLower()).ToLower();
                Logger.Info("扫码轮询-->RunCCBAge-->请求串-->" + request.ToJson());
                string response = _httpService.Post(request.ToJson(), _ApiUrl + "Api/v1.0/BarCodePay/codeCCBJHLXPay", 6);
                Logger.Info("扫码轮询-->RunCCBAge-->返回串-->" + response);
                ApiReturn apireturn = Json.ToObject<ApiReturn>(response);
                if (apireturn.result == 200)
                {
                    YardResponseResult check = Json.ToObject<YardResponseResult>(response);
                    string sign = MD5.MD5Encrypt(("[" + response.Split('[')[1].Split(']')[0] + "]").ToUpper() + apireturn.nonce.ToLower() + _MD5Key.ToLower()).ToLower();
                    if (sign != apireturn.sign)
                    {

                        return "扫码失败，返回结果验签错误";
                    }
                    return "支付成功";

                }
                else if (apireturn.result == 201)
                {
                    CCBJHPayResponseResult check = Json.ToObject<CCBJHPayResponseResult>(response);
                    string sign = MD5.MD5Encrypt(check.msg.ToJson().ToUpper() + apireturn.nonce.ToLower() + _MD5Key.ToLower()).ToLower();
                    if (sign != apireturn.sign)
                    {
                        return "扫码失败，返回结果验签错误";
                    }
                    cCBJHPayLX = check.msg;
                    return "等待轮询";
                }
                else
                {
                    return "支付失败";
                }
            }
            catch (Exception ex)
            {
                return "支付失败";
            }
        }
        #endregion

        #region 转换
        private int tradeCodetoCode(string QRCODETYPE)
        {
            if (QRCODETYPE == "龙支付")
            {
                return 1;
            }
            else if (QRCODETYPE == "微信")
            {
                return 2;
            }
            else if (QRCODETYPE == "支付宝")
            {
                return 3;
            }
            else if (QRCODETYPE == "银联")
            {
                return 4;
            }
            else
            {
                return 0;
            }
        }
        private string tradeCodetoStr(string QRCODETYPE)
        {
            /*
                1-	龙支付（暂不支持）
                2-	微信
                3-	支付宝
                4-	银联（暂不支持） 
             */
            if (QRCODETYPE == "1")
            {
                return "龙支付";
            }
            else if (QRCODETYPE == "2")
            {
                return "微信";
            }
            else if (QRCODETYPE == "3")
            {
                return "支付宝";
            }
            else if (QRCODETYPE == "4")
            {
                return "银联";
            }
            else
            {
                return "未知";
            }
        }
        #endregion

        #endregion

        #region 删除下载标识
        public async Task<bool> DeleteDownTag(long Station_Id, string IdList)
        {
            return await _aiYardDbTableIssuedCard.DeleteDownTag(Station_Id, IdList);
        }
        #endregion 

    }

}


